﻿using UnityEngine;
using System.Collections;
using Helper;

/// <summary>
/// 此脚本挂在走廊另一侧的门上
/// </summary>
public class RoomSwitch : MonoBehaviour {
	[SerializeField] string doorHandleName;
	DoorControler doorCtrl;
	[SerializeField] string targetDoorName1;
	Transform targetDoor1;
	[SerializeField] string targetDoorName2;
	Transform targetDoor2;

	[SerializeField] float minDis = 3f;
	public DoorControler oppositeDoor{
		get{ return doorCtrl;}
	}

	void Start () {
		doorCtrl = ItemManager.GetItemFlag (doorHandleName).GetComponent<DoorControler> ();
		targetDoor1 = ItemManager.GetItemFlag (targetDoorName1).transform;
		targetDoor2 = ItemManager.GetItemFlag (targetDoorName2).transform;
	}

	/// 交互函数，当物体与玩家产生交互时
	void OnInteraction(RaycastHit hit){
		if (hit.distance < minDis) {
			SwitchRoom ();
		}
	}
	void SwitchRoom(){
		ItemFlag targetObj = ItemManager.GetItemFlag ("Sys_Player");
		//距离调整
		Transform tr = targetObj.transform;
		Transform targetTran = (doorCtrl.openTime % 2 == 1) ? targetDoor1 : targetDoor2;
		Vector3 moveDir = targetTran.position - transform.position;
		tr.position += moveDir;
		//角度调整
		float diffAngle = Vector3.Angle (-targetTran.forward, transform.forward);
		Vector3 cross = Vector3.Cross (-targetTran.forward, transform.forward);
		diffAngle = cross.y <= 0f ? diffAngle : -diffAngle;
		tr.RotateAround (targetTran.position, targetTran.up, diffAngle);
		//关门
		doorCtrl.closeDoorSuddenly (false);
		//开门
		DoorControler nextDoorCtrl = targetTran.GetComponent<DoorControler>();
		nextDoorCtrl.OpenDoor ();
	}
}
